package com.tuling;

import java.io.IOException;
import java.util.List;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

/**
 * 订单服务 订单系统-订阅 -会员系统
 * 
 * @author wangningbo
 *
 */
public class OrderClient implements Watcher {
	private static Logger log = LoggerFactory.getLogger(OrderClient.class);
	private ZookeeperRegister register = new ZookeeperRegister();

	private String clientInfo;

	public OrderClient(String clientInfo) {
		this.clientInfo = clientInfo;
	}

	/**
	 * 订阅
	 * 
	 * @param cientInfo
	 */
	public void subscribe() {
		ZooKeeper zk = register.getConnection(this);
		try {
			List<String> nodeList = zk.getChildren(ZookeeperRegister.ROOT, true);
			if (nodeList.isEmpty()) {
				throw new RuntimeException("没有可用的会员系统服务");
			}

			for (String node : nodeList) {
				System.out.println(node);
				byte[] data = zk.getData(ZookeeperRegister.ROOT + "/" + node, true, null);
				NodeInfo nodeInfo = JSON.parseObject(new String(data), NodeInfo.class);

				if (null != nodeInfo && nodeInfo.getStatus().equals(NodeStatus.INIT)) {
					nodeInfo.setClientName(clientInfo);
					nodeInfo.setNum(nodeInfo.getNum() + 1);
					nodeInfo.setStatus(NodeStatus.RUN);
					zk.setData(ZookeeperRegister.ROOT + "/" + nodeInfo.getNode(),
							JSON.toJSONString(nodeInfo).getBytes(), -1);
				} else {
					log.info("没有找到可用的会员服务");
				}

			}
		} catch (KeeperException | InterruptedException e) {
			e.printStackTrace();
		}

	}

	@Override
	public void process(WatchedEvent event) {
		
		if(null == event){
			return ;
		}
		
		log.info("process - event :{}",  event.toString());
		
		EventType eventType = event.getType();
		
		if (event.getState() == KeeperState.SyncConnected) {
			
		}
		
		/*if (eventType == EventType.NodeChildrenChanged) {
			// 如果节点改变 , 重新订阅节点
			subscribe();
		} else if(eventType == EventType.NodeCreated){
			//如果有新增节点
			String path = event.getPath();
			log.info("create event -->节点为: {}", path);
		}*/
	}

	public static void main(String[] args) {
		OrderClient client = new OrderClient("orderServer01");
		client.subscribe();
		try {
			System.in.read();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
